<?php

namespace App\Services;

use App\Exceptions\BaseException;
use App\Models\AuthenticLog;
use App\Models\Goods;
use App\Models\MemberOther;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use Illuminate\Support\Facades\Log;

class EsignService
{
    //合同签署状态
    const ESIGN_STATUS_DRAFT = 0;//草稿
    const ESIGN_STATUS_SIGNING = 1;//签署中
    const ESIGN_STATUS_FINISH = 2;//完成
    const ESIGN_STATUS_CANCEL = 3;//撤销
    const ESIGN_STATUS_OVERDUE = 5;//过期
    const ESIGN_STATUS_REFUSE = 7;//拒签

    //合同签署模板
    const ESIGN_SHOP_TWO = 1;//平台两方合同
    const ESIGN_SELF_TWO = 2;//自营两方合同
    const ESIGN_SHOP_THREE = 3;//三方合同



    //获取鉴权Token
    public static function getToken(){
        $arr = array("appId"=>config('esignDlz.APPID'),"secret"=>config('esignDlz.SECRET'),"grantType"=>config('esignDlz.GRANT_TYPE'));
        $data = json_encode($arr);
        $getToken=config('esignDlz.getToken')."?appId=".config('esignDlz.APPID')."&secret=".config('esignDlz.SECRET')."&grantType=".config('esignDlz.GRANT_TYPE');
        $return_content = self::doGet($getToken,$data);
        $result = (array)json_decode($return_content,true);
        if(isset($result['data'])){
            $data2 = $result['data'];
            $stokren = $data2['token'];
        }else{
            $stokren = '';
        }

        return $stokren;
    }

    //创建个人账户
    public static function addPersonAccountID($thirdPartyUserId,$name,$idNumber,$mobile){
        $arr = array(
            'thirdPartyUserId'=>$thirdPartyUserId,
            'name'=>$name,
            'idNumber'=>$idNumber,
            'idType'=>'CRED_PSN_CH_IDCARD',
            'mobile'=>$mobile);
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.addPersonAccountID'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建个人账户',$data,$return_content);
        return $result;
    }
    /**
     * 布尔-个人信信息报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createBoolDlzUserAuth($order){

        //发起签署
        //MD5 RXZ2hNbCifOcMNuHMvw+vQ==
        $templateId = config('boolean.esign_dlz_template_id');//个人信用报告授权书模板ID
        $cert_name = isset($order['cert_name'])?$order['cert_name']:'夏克晓';

        $order_arr = array(
            'name'=>'个人信息报告授权书.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $cert_name, //姓名
                "company_name" => '瑞安市诺明网络科技有限公司', //公司
                "year" => date("Y"),
                "month" => date("m"),
                "day" => date("d")
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            if(empty($order['esign_user_id'])){
                $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
                $data1 = $result['data'];
                if(!empty($data1['accountId'])){
                    $esign_user_id = $data1['accountId'];
                    MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
                }
            }
            $order['esign_seal_id']=$esign_user_id;
            self::SetSignAuth($esign_user_id);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '个人信息报告授权书.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '个人信息报告授权书';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_BOOl_AUTH_USER;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 470;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 145;
        // dd($step_data);
        $data = json_encode($step_data,JSON_UNESCAPED_UNICODE);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-个人信息报告授权书aaaaa',$data,$result);

        return $result;

    }


    //签署流程查询
    public static function signStatus($fileId){
        $addaDocumnet = str_replace('{flowId}',$fileId,config('esignDlz.signStatus'));
        $return_content = self::get_data($addaDocumnet,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('签署流程查询',$addaDocumnet,$return_content);
        if(!empty($result['data'])){
            return $result['data'];
        }
    }

    //获取签署地址
    public static function executeUrl($flowId,$accountId){
        $addaDocumnet = str_replace('{flowId}',$flowId,config('esignDlz.executeUrl'));
        $url = $addaDocumnet.'?accountId='.$accountId;
        $return_content = self::get_data($url,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('获取签署地址',$addaDocumnet,$return_content);
        if(isset($result['data']) && !empty($result['data']['url'])){
            return $result['data']['url'];
        }
    }

    //修改个人签署账号
    public static function updateAccounts($accountId,$mobile,$name){
        $addaDocumnet = str_replace('{accountId}',$accountId,config('esignDlz.updateAccounts'));
        $arr = array(
            'mobile'=>$mobile,
            'name'=>$name
        );
        $data = json_encode($arr);
        $return_content = self::sendHttpPUTCommon($addaDocumnet,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('修改个人签署账号',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['accountId'])){
            return $result['data']['accountId'];
        }
    }

    // 1 创建企业法人账号
    public static function addFaAccountID($thirdPartyUserId,$name,$idNumber,$mobile){
        $arr = array(
            'thirdPartyUserId'=>$thirdPartyUserId,
            'name'=>$name,
            'idNumber'=>$idNumber,
            'idType'=>'CRED_PSN_CH_IDCARD',
            'mobile'=>$mobile
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.addPersonAccountID'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建企业法人账号',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['accountId'])){
            return $result['data']['accountId'];
        }
    }

    // 2 创建平台账号
    public static function addTerraceAccountId($thirdPartyUserId,$creator,$name,$idNumber){
        $arr = array(
            'thirdPartyUserId'=>$thirdPartyUserId,
            'creator'=>$creator,
            'name'=>$name,
            'idType'=>"CRED_ORG_USCC",
            'idNumber'=>$idNumber
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.addOrganizeAccountID'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建平台账号',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['orgId'])){
            return $result['data']['orgId'];
        }
    }

    // 3 创建机构模板印章
    public static function addOrganizeSeals($orgId){
        $addaDocumnet = str_replace('{orgId}',$orgId,config('esignDlz.addOrganizeSeals'));
        $arr = array(
            'color'=>'RED',
            'type'=>'TEMPLATE_ROUND',
            'central'=>"STAR"
        );
        $data = json_encode($arr);
        $return_content = self::doPost($addaDocumnet,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建机构模板印章',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['sealId'])){
            return $result['data']['sealId'];
        }
    }

    //三方合同签署
    public static function createFlowOneStepShopThree($order,$shop_user,$esign_user_id){
        $templateId = config('esignDlz.TEMPLATE_ID');//三方
        //支付类型;  1智能合同代扣；2预授权； 3花呗 4 全额买断
        if ($order['pay_type']==1){
            $pay_type='智能合同代扣';
        }elseif ($order['pay_type']==2){
            $pay_type='预授权';
        }elseif ($order['pay_type']==3){
            $pay_type='花呗';
        }elseif ($order['pay_type']==4){
            $pay_type='全额买断';
        }else{
            $pay_type='未知';
        }
        //买断价
//        $order['isBuyout'] = $order['is_buy_out'];
//        $order['is_buy_out'] = GoodsService::getGoodsBuyoutName($order['is_buy_out']);
        $fisrt_month_rent = OrderLease::where('order_id',$order['id'])->where("which_period",1)->value("rent");
        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }
        $order_arr = array(
            'name'=>'租赁合同',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                'order_sn' => $order['trade_no'],
                'first_name' => $shop_user['mechanism'],
                'first_address' => str_replace('-','',$shop_user['company_area']).$shop_user['company'],
//                'first_address' => $shop_user['company'],
                'first_code' => $shop_user['companyid'],
                'first_mobile' => $shop_user['contact_tel'],
                'user_name' => $order['cert_name'],
                'user_address' => $order['address'],
                'user_idcard' => $order['cert_no'],
                'user_mobile' => $order['user_mobile'],
                'third_name' => '瑞安市诺明网络科技有限公司',
                'third_address' => '浙江省温州市瑞安市玉海街道解放中路118号（后半间）',
                'third_code' => '91330381MAC65FWH5X',
                'third_mobile' => '19357616167',
                'order_no' => $order['trade_no'],
                'user_data' => $order['cert_name'].'('.$order['cert_no'].')',
                'goods_name' => $order['goods_title'],
                'setmeal_name' => $order['setmeal_title'],
                'amount' => $order['amount'],
                // 'setmeal_foregift' => $order['setmeal_foregift'],
                'is_new' => $order['new_grade']<100?'否':'是',
                'meal' => $order['pact_type'],
                'goods_price' => $order['website_price'].'元',
                // 'total_rent' => sprintf("%.2f",$order['website_price']*$order['amount']).'元',
                'total_rent1' => $order['rent_total'].'元',
                // 'month_rent' => sprintf("%.2f",$order['rent_total']/$order['month_total']).'元',
                'first_month_rent'=>$fisrt_month_rent,
                'month_rent' => $month_rent.'元'.'（月租金=(总租金-首付金)/期数）',
                'lease_term' =>  date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time'])),
                'pay_type' => '分期付租',
                'amount_pay' => $order['isBuyout']==1?$order['setmeal_foregift'].'元':$order['is_buy_out'],
                'buy_out_price' => '0.00元',
                'receiving_address' => $order['address'],
                'user_name1' => $order['cert_name'],
                'user_mobile1' => $order['user_mobile'],
                'user_address1' => $order['address'],
                'email'=>$order['user_email'],
                'first_name1' => $shop_user['mechanism'],
                'first_mobile1' => $shop_user['contact_tel'],
                'first_address1' => $shop_user['company'],
                'first_name2' => $shop_user['mechanism'],
                'user_name2' => $order['cert_name'],
                'third_name2' => '瑞安市诺明网络科技有限公司',
                'sign_year' => date("Y"),
                'sign_month' => date("m"),
                'sign_day' => date("d"),
                'insurance_price' => GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']).'元（与第一期租金一并支付）',
            )
        );

        $orderLease = OrderLease::getPayTime($order);
        foreach ($orderLease as $k=>$v){
            $order_arr['simpleFormFields']['pay_time'.$v['which_period']] = date('Y年m月d日',$v['begin_time']);
            $order_arr['simpleFormFields']['month_rent'.$v['which_period']] = $v['rent'].'元';
        }
        if(count($orderLease) < 12){
            $lastNum = count($orderLease)+1;
            for($i=$lastNum;$i<=12;$i++){
                $order_arr['simpleFormFields']['pay_time'.$i] = '---';
                $order_arr['simpleFormFields']['month_rent'.$i] = '---';
            }
        }


        $fileId = self::createByTemplate($order_arr);
        if(!empty($shop_user['esign_shop_id'])){
            self::SetSignAuth($shop_user['esign_shop_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'商户签署账号不存在'];
        }
        //发起签署
        $arr = array(
            'docs' => array(
                0 => array(
                    'fileId' => $fileId,
                    'fileName' => '都来租租赁合同.pdf'
                )
            ),
            'flowInfo' => array(
                'autoArchive' => true,
                'autoInitiate' => true,
                'businessScene' => '租赁合同',
                'flowConfigInfo' => array(
                    'redirectUrl' => 'wechat://back',
                    'noticeDeveloperUrl' => config('alipay.callbackDomain').CommonService::NOTICE_WX_URL_CONTRACT,
                    'willTypes'=>['FACE_WE_CHAT_FACE']
                ),
                'initiatorAccountId' => config('esignDlz.ACCOUNT'),
                'initiatorAuthorizedAccountId' => config('esignDlz.ACCOUNT')
            ),
            'signers' => array(
                //企业自动签署
                0=>array(
                    'platformSign' => false,
                    'signerAccount' => array(
                        'authorizedAccountId' => $shop_user['esign_shop_id'],
                    ),
                    'signfields' => array(
                        0=>array(
                            'autoExecute' => true,
                            'actorIndentityType' => 2,
                            'fileId' => $fileId,
                            'sealType' => 2,
                            'sealId' => $shop_user['esign_seal_id'],
                            'posBean' => array(
                                'posPage' => 16,
                                'posX' => 190,
                                'posY' => 679
                            )
                        )
                    )
                ),
                //个人手动签署
                1=>array(
                    'signerAccount' => array(
                        'signerAccountId' => $esign_user_id,
                    ),
                    'signfields' => array(
                        0=> array(
                            'autoExecute' => false,
                            'fileId' => $fileId,
                            'sealType' => 0,
                            'handDrawnWay'=>1,
                            'posBean' => array(
                                'posPage' => 16,
                                'posX' => 190,
                                'posY' => 560
                            )
                        )
                    )
                ),
                //平台自动签署
                2=>array(
                    'platformSign' => false,
                    'signerAccount' => array(
                        'authorizedAccountId' => config('esignDlz.ACCOUNT'),
                    ),
                    'signfields' => array(
                        0=>array(
                            'autoExecute' => true,
                            'actorIndentityType' => 2,
                            'fileId' => $fileId,
                            'sealType' => 2,
                            'sealId' => config('esignDlz.SEALID'),
                            'posBean' => array(
                                'posPage' => 16,
                                'posX' => 190,
                                'posY' => 430
                            )
                        )
                    )
                )
            ),
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('一步发起签署-三方合同',$data,$return_content);
        return $result;
    }

    //通过上传方式创建模板
    public static function createByUploadUrl(){
        $filePath = '/www/wwwroot/www.doulaizu.com/个人信息授权书qnyp（通用版2024.10.15)_20241016105348.pdf';//合同模板地址 需要上传oss
        $contentMd5 = base64_encode(md5_file($filePath,true));
        $arr = array(
            'contentMd5'=>$contentMd5,
            'contentType'=>'application/pdf',
            'fileName'=>'个人信息授权书.pdf',
            'convert2Pdf'=>false
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.createByUploadUrl'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('通过上传方式创建模板',$data,$return_content);
        $data2=$result['data'];
        if($data2['templateId']){
            $templateId = $data2['templateId'];
            $uploadUrl = $data2['uploadUrl'];
            $fileContent = file_get_contents($filePath);
            $res = self::sendHttpPUT($uploadUrl,$contentMd5,$fileContent);
            self::addLog('上传文件流',['contentMd5'=>$contentMd5],$res);
            if($res == 200){
                print_r($templateId);die;
            }else{
                print_r($res);die;
            }
        }else{
            print_r($result);die;
        }
    }

    //创建个人模板印章
    public static function personaltemplate($accountId,$user_name){
        $addaDocumnet = str_replace('{accountId}',$accountId,config('esignDlz.personaltemplate'));
        $arr = array(
            'alias'=>$user_name,
            'color'=>'RED',
            'type'=>"BORDERLESS"
        );
        $data = json_encode($arr);
        $return_content = self::doPost($addaDocumnet,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建个人模板印章',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['sealId'])){
            return $result['data']['sealId'];
        }
    }

    //通过模板创建文件
    public static function createByTemplate($arr){
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.createByTemplate'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        if(isset($result['data']) && !empty($result['data']['fileId'])){
            return $result['data']['fileId'];
        }else{
            return $result;
        }
    }

    //设置静默签署
    public static function SetSignAuth($esign_account_id){
        $addaDocumnet = str_replace('{accountId}',$esign_account_id,config('esignDlz.SetSignAuth'));
        $return_content = self::doPost($addaDocumnet,'',config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        if($result && !empty($result['data']['docs'])){
            $result_data = $result['data']['docs'];
            return $result_data[0];
        }
    }

    //签署流程撤销
    public static function revoke($flowId){
        $addaDocumnet = str_replace('{flowId}',$flowId,config('esignDlz.revoke'));
        $arr = array(
            'operatorId' => config('esignDlz.ACCOUNT')
        );
        $data = json_encode($arr);
        $return_content = self::sendHttpPUTCommon($addaDocumnet,$data,config('esignDlz.APPID'),self::getToken());
        return $return_content;
    }

    public static function downloadDocument($flowid){
        $downloadDocument = str_replace('{flowId}',$flowid,config('esignDlz.downloadDocument'));
        $return_content = self::get_data($downloadDocument,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('下载文件',['flow_id'=>$flowid],$result);

        if($result && !empty($result['data']['docs'])){
            $result_data = $result['data']['docs'];
            return $result_data[0];
        }
    }


    public static function get_data($url, $appID, $stoken) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }

    public static function doGet($url, $data)
    {
        list($return_code, $return_content) = self::curl_get_https($url, $data);
        return $return_content;
    }



    public static function http_post_wx_data($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID,"X-Tsign-Dns-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
//        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }


    public static function doPost($url, $data, $appID, $stoken)
    {
        list($return_code, $return_content) = self::http_post_data($url, $data, $appID,$stoken);

        return $return_content;
    }

    public static function http_post_data($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public static function doGeta($url, $data,$appID, $stoken)
    {
        list($return_code, $return_content) = self::http_sign_get_data($url, $data, $appID, $stoken);
        return $return_content;
    }

    public static function http_sign_get_data($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json;charset=UTF-8" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }


    public static function curl_get_https($url, $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public static function sendHttpPUT($uploadUrls, $contentMd5, $fileContent){
        $header = array(
            'Content-Type:application/pdf',
            'Content-Md5:' . $contentMd5
        );

        $status = '';
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $uploadUrls);
        curl_setopt($curl_handle, CURLOPT_FILETIME, true);
        curl_setopt($curl_handle, CURLOPT_FRESH_CONNECT, false);
        curl_setopt($curl_handle, CURLOPT_HEADER, true); // 输出HTTP头 true
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle, CURLOPT_TIMEOUT, 5184000);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 120);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT');

        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $fileContent);
        $result = curl_exec($curl_handle);
        $status = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);

        if ($result === false) {
            $status = curl_errno($curl_handle);
            $result = 'put file to oss - curl error :' . curl_error($curl_handle);
        }
        curl_close($curl_handle);
        return $status;
    }

    public static function sendHttpPUTCommon($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }


    /**
     * E签宝合同
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::channel("esign")->debug($message,$content);
    }


    //【人脸识别认证】个人实名-唤起
    public static function checkFaceAuth($accountId,$cert_string,$type,$orderId){
        $faceAuth = str_replace('{accountId}',$accountId,config('esignDlz.faceAuth'));

        //认证结束后异步通知地址
        if($type == '1'){ //下单
//            $arr = array(
//                'faceauthMode'=>'ESIGN',
//                'callbackUrl'=>'https://h5.doulaizuji.com/order.html',//认证完成后重定向地址
//                'contextId'=>$cert_string //自定义业务标识
//            );
            $arr = array(
                'faceauthMode'=>'ZHIMACREDIT',
                'callbackUrl'=>'1',//认证完成后重定向地址
                'contextId'=>$cert_string //自定义业务标识
            );
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL;
        }else if($type == '2'){ //签署合同

             $arr = array(
                    'faceauthMode'=>'ESIGN',
                    'callbackUrl'=>'https://h5.doulaizuji.com/sign.html?order_id='.$orderId,//认证完成后重定向地址
                    'contextId'=>$cert_string //自定义业务标识
                );
//            $arr = array(
//                'faceauthMode'=>'ZHIMACREDIT',
//                'callbackUrl'=>config('alipay.callbackDomain').CommonService::AUTH_FACE_URL,//认证完成后重定向地址
//                'contextId'=>$cert_string //自定义业务标识
//            );
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL_SIGN;
        }
        $data = json_encode($arr);
        $return_content = self::doPost($faceAuth,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        // echo '<pre>';
        // print_r($result);
        // dd(1);
        self::addLog('个人实名认证',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }
    }


    //查询个人刷脸状态
    public static function checkFaceStatusAuth($accountId){
        $faceAuthStatus = str_replace('{accountId}',$accountId,config('esignDlz.faceAuthStatus'));
        $arr=[];
        $data = json_encode($arr);
        $return_content = self::doGeta($faceAuthStatus,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('个人实名认证状态',['flow_id'=>$accountId],$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['status'])){
            return $result['data'];
        }
    }



    //【人脸识别认证】个人实名-web唤起
    public static function checkWechatWebFaceAuth($accountId,$cert_string,$type){
        $faceAuth = str_replace('{accountId}',$accountId,config('esignDlz.faceWebAuth'));
        $arr = array(
            'redirectUrl'=>'wechat://back',//认证完成后重定向地址
            'contextId'=>$cert_string //自定义业务标识
        );
        //认证结束后异步通知地址
        if($type == '1'){ //下单
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_WXFACE_URL;
        }else if($type == '2'){ //签署合同
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL_SIGN;
        }
        $data = json_encode(['contextInfo'=>$arr, 'authType'=>'PSN_FACEAUTH_BYURL','availableAuthTypes'=>["PSN_FACEAUTH_BYURL"]]);
        $return_content = self::http_post_wx_data($faceAuth,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        // echo '<pre>';
        // print_r($result);
        // dd($result);
        self::addLog('个人实名认证',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }
    }

    //【人脸识别认证】个人实名-查询
    public static function selectFaceAuth($flowId){
        $faceAuthPhoto = str_replace('{flowId}',$flowId,config('esignDlz.faceAuthPhoto'));
        $arr = array();
        $data = json_encode($arr);
        $return_content = self::doGeta($faceAuthPhoto,$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('人脸识别认证返照',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }
    }

    /**
     * 查看人脸图片
     * @param $flowId
     * @return mixed|void
     */
    public static function findFace($flowId,$accountId){
        $arr = array(
            'accountId'=>$accountId,//认证完成后重定向地址
            'flowId'=>$flowId //自定义业务标识
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.faceImage'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
var_dump($data);
var_dump($return_content);
        self::addLog('查询签署中认证信息',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['identityFlowId'])){
            return $result['data'];
        }
    }

     /**
     * 征信-个人信用报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createIncestUserAuth($order){

        //发起签署
        //MD5 RXZ2hNbCifOcMNuHMvw+vQ==
        $templateId = config('esignDlz.TEMPLATE_ID_6');//个人信用报告授权书模板ID
        $cert_name = isset($order['cert_name'])?$order['cert_name']:'夏克晓';
        $cert_no = isset($order['cert_no'])?$order['cert_no']:'330381198602116113';
        $mobile = isset($order['mobile'])?$order['mobile']:'13967763998';
        $order_arr = array(
            'name'=>'个人信用报告授权书.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $cert_name, //姓名
        		"mobile" => $mobile, //电话
        		"cert" => $cert_no, //身份证号
        		"choose"=>"√",
        		"year" => date("Y"),
        		"month" => date("m"),
        		"day" => date("d")
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'个人签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '个人信用报告授权书.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '个人信用报告授权书';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_AUTH_USER;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 470;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 145;
        // dd($step_data);
        $data = json_encode($step_data);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-个人信用报告授权书',$data,$return_content);

        return $result;

    }

    /**
     * 征信-用户授权协议
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createCreditAuth($order){

        //发起签署
        $templateId = config('esignDlz.TEMPLATE_ID_2');//用户授权协议模板ID
        $order_arr = array(
            'name'=>'用户授权协议.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                'name' => $order['cert_name'],
                'cert' => $order['cert_no'],
                'mobile' => $order['user_mobile'],
        		"year" => date("Y"),
        		"month" => date("m"),
        		"day" => date("d")
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'个人签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '用户授权协议.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '用户授权协议';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_SLIENCE;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 390;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 115;

        $data = json_encode($step_data);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-用户授权协议',$data,$return_content);

        return $result;

    }

    /**
     * 征信-融资租赁委托担保合同
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createCreditCompanyAuth($order,$orgid,$seal_id){

        //发起签署
        $templateId = config('esignDlz.TEMPLATE_ID_3');//融资租赁委托担保合同模板ID
        $order_arr = array(
            'name'=>'融资租赁委托担保合同.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
		        "platformLoanNo"=>$order['trade_no'],
                'name' => $order['cert_name'],
                'idcardNumber' => $order['cert_no'],
                'mobile' => $order['user_mobile'],
                'website' => '挺想租',
                'loanStartDate' => date('Y年m月d日'),
                'partner' => $order['mechanism'],
                'payMoney' => sprintf("%.2f",$order['rent_total']/$order['month_total']).'元', //每月租金
                'periodNum' => $order['month_total'],  //总租期
                'buyoutPriceMoney' => sprintf("%.2f",$order['setmeal_foregift']-$order['rent_total']),  //买断款
                'loanMoney' => $order['rent_total'],  //总租金
        		"guaranteeRate"=>"0.01%",//担保费率
        		"guaranteeFee"=>sprintf("%.2f",$order['rent_total']*0.0001), //担保费用
                'currentDateYmd' => date('Y年m月d日')
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($orgid)){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth($orgid);//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '融资租赁委托担保合同.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '融资租赁委托担保合同';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_COMPANY;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        // $step_data['signers'][0]['signerAccount']['authorizedAccountId'] = $orgid;
        // $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        // $step_data['signers'][0]['signfields'][0]['actorIndentityType'] = 2;
        // $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        // $step_data['signers'][0]['signfields'][0]['sealType'] = 2;

        // $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 5;
        // $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 185;
        // $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 173;

        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 5;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 400;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 100;
        // dd($step_data);
        $data = json_encode($step_data);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());

        $result = (array)json_decode($return_content,true);
        // dd($result);
        self::addLog('一步发起签署-融资租赁委托担保合同',$data,$return_content);

        return $result;

    }


    /**
     * 布尔-个人信信息报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createBoolUserAuth($order){

        //发起签署
        //MD5 RXZ2hNbCifOcMNuHMvw+vQ==
        $templateId = config('boolean.esign_template_id');//个人信用报告授权书模板ID
        $cert_name = isset($order['cert_name'])?$order['cert_name']:'夏克晓';

        $order_arr = array(
            'name'=>'个人信息报告授权书.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $cert_name, //姓名
                "company_name" => '瑞安市诺明网络科技有限公司', //公司
                "year" => date("Y"),
                "month" => date("m"),
                "day" => date("d")
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            if(empty($order['esign_user_id'])){
                $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
                $data1 = $result['data'];
                if(!empty($data1['accountId'])){
                    $esign_user_id = $data1['accountId'];
                    MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
                }
            }
            $order['esign_seal_id']=$esign_user_id;
            self::SetSignAuth($esign_user_id);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '个人信息报告授权书.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '个人信息报告授权书';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_BOOl_AUTH_USER;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 470;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 145;
        // dd($step_data);
        $data = json_encode($step_data,JSON_UNESCAPED_UNICODE);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-个人信息报告授权书',$data,$result);

        return $result;

    }

    /**
     * 2024征信-个人信用报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createIncestUserAuthCall($order){
        //发起签署
        //MD5 RXZ2hNbCifOcMNuHMvw+vQ==
        $templateId = config('esignDlz.TEMPLATE_ID_7');//个人信用报告授权书模板ID
        $cert_name = isset($order['cert_name'])?$order['cert_name']:'夏克晓';
        $cert_no = isset($order['cert_no'])?$order['cert_no']:'330381198602116113';
        $mobile = isset($order['mobile'])?$order['mobile']:'13967763998';
        $order_arr = array(
            'name'=>'个人信用报告授权书.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $cert_name, //姓名
                "mobile" => $mobile, //电话
                "cert_no" => $cert_no, //身份证号
                "companyname"=>"都来租物",
                "companymobile"=>"19357616167",
                "date" => date("Y年m月d日"),
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'个人签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '个人信用报告授权书.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '个人信用报告授权书';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_AUTH_USER_Call;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esignDlz.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esignDlz.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 460;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 110;
        // dd($step_data);
        $data = json_encode($step_data);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-2024个人信用报告授权书',$data,$return_content);

        return $result;

    }

    public static function createFlowOneStepShopFour($order,$shop_user,$esign_user_id){
        $templateId = config('esignDlz.TEMPLATE_FOUR_ID');//四方
        $fisrt_month_rent = OrderLease::where('order_id',$order['id'])->where("which_period",1)->value("rent");
        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }

        $orderLease = OrderLease::where('order_id',$order['id'])->select('id','begin_time','rent','which_period')->orderBy('id','asc')->get()->toArray();
        $repayList=[];
        foreach ($orderLease as $key=>$ra){
            $key=$key+1;
            $repayStrategyList=[
                'paymentterm'.$key => $ra['which_period'],
                "periodfee".$key => $ra['rent'].'元',
                "perioddate".$key => date('Y-m-d',$ra['begin_time']),
            ];
            $repayList=array_merge($repayList,$repayStrategyList);
        }

        if($order['prepayment_total']==1){
            $cash_pledge=0;
            $cash_pledge_period=$order['month_total'];
            $cash_pledge_deduction='';
        }else if($order['prepayment_total']>1){
            $cash_pledge=bcmul($order['prepayment_total']-1,$month_rent,2);
            $cash_pledge_period=$order['month_total']-$order['prepayment_total']+1;
            $num=$order['prepayment_total']-1;

            for ($i=0;$i<$num;$i++){
                $key=$order['month_total']-$i-1;
                if($i==0){
                    $cash_pledge_deduction=$orderLease[$key]['which_period'].$cash_pledge_deduction;
                }else{
                    $cash_pledge_deduction=$orderLease[$key]['which_period'].','.$cash_pledge_deduction;
                }
            }
        }



        $order_arr = array(
            'name'=>'租赁合同',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $order['cert_name'], //姓名
                "mobile" => $order['user_mobile'], //电话
                "cert_no" => $order['cert_no'], //身份证号
                "card_no" => $order['cert_no'], //身份证号
                "companyname"=>'瑞安市诺明网络科技有限公司',
                "date" => date("Y年m月d日"),
                'goods_price' => $order['website_price'].'元',
                'order_sn' => $order['trade_no'],
                'user_name' => $order['cert_name'],
                'user_address' => $order['address'],
                'user_idcard' => $order['cert_no'],
                'user_mobile' => $order['user_mobile'],
                'jiaf' => '环宇融信（天津）融资租赁有限公司',
                'dingf' => '重庆秋惠信息科技有限公司',
                'third_name' => '瑞安市诺明网络科技有限公司',
                'third_address' => '浙江省温州市瑞安市玉海街道解放中路118号（后半间）',
                'third_code' => '91330381MAC65FWH5X',
                'third_mobile' => '19357616167',
                'order_no' => $order['trade_no'],
                'user_data' => $order['cert_name'].'('.$order['cert_no'].')',
                'goods_name' => $order['goods_title'],
                'setmeal_name' => $order['setmeal_title'],
                'amount' => $order['amount'],
                'setmeal_foregift' => $order['setmeal_foregift'],
                'is_new' => $order['new_grade']<100?'否':'是',
                'meal' => $order['pact_type'],
                'total_rent1' => $order['rent_total'].'元',
                'month_total' => $order['month_total'],
                'first_month_rent'=>$fisrt_month_rent,
                'month_rent' => $month_rent.'元'.'（月租金=(总租金-首付金)/期数）',
                'begin_time' =>  date('Y.m.d',strtotime($order['begin_time'])),
                'end_time'=>date('Y.m.d',strtotime($order['end_time'])),
                'lease_term' =>  date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time'])),
                'setmeal_price' => $order['setmeal_price']>0?$order['setmeal_price']:0,
                'user_name1' => $order['cert_name'],
                'user_mobile1' => $order['user_mobile'],
                'user_address1' => $order['address'],
                'email'=>$order['user_email'],
                'first_name' => $shop_user['mechanism'],
                'cash_pledge'=>$cash_pledge,//押金
                'cash_pledge_period'=>$cash_pledge_period,//押金的第几期
                'cash_pledge_deduction'=>$cash_pledge_deduction,//抵充的第几期
            )
        );

        $order_arr['simpleFormFields']=array_merge($order_arr['simpleFormFields'],$repayList);


        $orderLease = OrderLease::getPayTime($order);
        foreach ($orderLease as $k=>$v){
            $order_arr['simpleFormFields']['pay_time'.$v['which_period']] = date('Y年m月d日',$v['begin_time']);
            $order_arr['simpleFormFields']['month_rent'.$v['which_period']] = $v['rent'].'元';
        }
        if(count($orderLease) < 12){
            $lastNum = count($orderLease)+1;
            for($i=$lastNum;$i<=12;$i++){
                $order_arr['simpleFormFields']['pay_time'.$i] = '---';
                $order_arr['simpleFormFields']['month_rent'.$i] = '---';
            }
        }


        $fileId = self::createByTemplate($order_arr);
        if(!empty($shop_user['esign_shop_id'])){
            self::SetSignAuth($shop_user['esign_shop_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'商户签署账号不存在'];
        }
        //发起签署
        $arr = array(
            'docs' => array(
                0 => array(
                    'fileId' => $fileId,
                    'fileName' => '都来租租赁合同.pdf'
                )
            ),
            'flowInfo' => array(
                'autoArchive' => true,
                'autoInitiate' => true,
                'businessScene' => '租赁合同',
                'flowConfigInfo' => array(
                    'redirectUrl' => 'wechat://back',
                    'noticeDeveloperUrl' => config('alipay.callbackDomain').CommonService::NOTICE_WX_URL_CONTRACT,
                    'willTypes'=>['FACE_WE_CHAT_FACE']
                ),
                'initiatorAccountId' => config('esignDlz.ACCOUNT'),
                'initiatorAuthorizedAccountId' => config('esignDlz.ACCOUNT')
            ),
            'signers' => array(
                //企业自动签署
//                0=>array(
//                    'platformSign' => false,
//                    'signerAccount' => array(
//                        'authorizedAccountId' => $shop_user['esign_shop_id'],
//                    ),
//                    'signfields' => array(
//                        0=>array(
//                            'autoExecute' => true,
//                            'actorIndentityType' => 2,
//                            'fileId' => $fileId,
//                            'sealType' => 2,
//                            'sealId' => $shop_user['esign_seal_id'],
//                            'posBean' => array(
//                                'posPage' => 16,
//                                'posX' => 190,
//                                'posY' => 679
//                            )
//                        )
//                    )
//                ),
                //个人手动签署
                0=>array(
                    'signerAccount' => array(
                        'signerAccountId' => $esign_user_id,
                    ),
                    'signfields' => array(
                        0=> array(
                            'autoExecute' => false,
                            'fileId' => $fileId,
                            'sealType' => 1,
                            'handDrawnWay'=>1,
                            'posBean' => array(
                                'posPage' => 17,
                                'posX' => 412,
                                'posY' => 216
                            )
                        )
                    )
                ),
                //平台自动签署
                1=>array(
                    'platformSign' => false,
                    'signerAccount' => array(
                        'authorizedAccountId' => config('esignDlz.ACCOUNT'),
                    ),
                    'signfields' => array(
                        0=>array(
                            'autoExecute' => true,
                            'actorIndentityType' => 2,
                            'fileId' => $fileId,
                            'sealType' => 2,
                            'sealId' => config('esignDlz.SEALID'),
                            'posBean' => array(
                                'posPage' => 17,
                                'posX' => 145,
                                'posY' => 99
                            )
                        )
                    )
                ),
                2=>array(
                    'signerAccount' => array(
                        'signerAccountId' => $esign_user_id,
                    ),
                    'signfields' => array(
                        0=> array(
                            'autoExecute' => false,
                            'fileId' => $fileId,
                            'sealType' => 1,
                            'handDrawnWay'=>1,
                            'posBean' => array(
                                'posPage' => 21,
                                'posX' => 420,
                                'posY' => 414
                            )
                        )
                    )
                ),
            ),
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
//        dd($return_content);
        $result = (array)json_decode($return_content,true);
        self::addLog('一步发起签署-三方合同',$data,$return_content);
        return $result;
    }



    public static function createFlowOneStepShopSupplierFour($order,$shop_user,$esign_user_id){
        $templateId = config('esignDlz.TEMPLATE_FOUR_ID');//四方
        $fisrt_month_rent = OrderLease::where('order_id',$order['id'])->where("which_period",1)->value("rent");
        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }

        $orderLease = OrderLease::where('order_id',$order['id'])->select('id','begin_time','rent','which_period')->orderBy('id','asc')->get()->toArray();
        $repayList=[];
        foreach ($orderLease as $key=>$ra){
            $key=$key+1;
            $repayStrategyList=[
                'paymentterm'.$key => $ra['which_period'],
                "periodfee".$key => $ra['rent'].'元',
                "perioddate".$key => date('Y-m-d',$ra['begin_time']),
            ];
            $repayList=array_merge($repayList,$repayStrategyList);
        }

        if($order['prepayment_total']==1){
            $cash_pledge=0;
            $cash_pledge_period=$order['month_total'];
            $cash_pledge_deduction='';
        }else if($order['prepayment_total']>1){
            $cash_pledge=bcmul($order['prepayment_total']-1,$month_rent,2);
            $cash_pledge_period=$order['month_total']-$order['prepayment_total']+1;
            $num=$order['prepayment_total']-1;

            for ($i=0;$i<$num;$i++){
                $key=$order['month_total']-$i-1;
                if($i==0){
                    $cash_pledge_deduction=$orderLease[$key]['which_period'].$cash_pledge_deduction;
                }else{
                    $cash_pledge_deduction=$orderLease[$key]['which_period'].','.$cash_pledge_deduction;
                }
            }
        }



        $order_arr = array(
            'name'=>'租赁合同',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "name" => $order['cert_name'], //姓名
                "mobile" => $order['user_mobile'], //电话
                "cert_no" => $order['cert_no'], //身份证号
                "card_no" => $order['cert_no'], //身份证号
                "companyname"=>'瑞安市诺明网络科技有限公司',
                "date" => date("Y年m月d日"),
                'goods_price' => $order['website_price'].'元',
                'order_sn' => $order['trade_no'],
                'user_name' => $order['cert_name'],
                'user_address' => $order['address'],
                'user_idcard' => $order['cert_no'],
                'user_mobile' => $order['user_mobile'],
                'jiaf' => '环宇融信(天津)融资租赁有限公司',
                'dingf' => '重庆秋惠信息科技有限公司',
                'third_name' => '瑞安市诺明网络科技有限公司',
                'third_address' => '浙江省温州市瑞安市玉海街道解放中路118号（后半间）',
                'third_code' => '91330381MAC65FWH5X',
                'third_mobile' => '19357616167',
                'order_no' => $order['trade_no'],
                'user_data' => $order['cert_name'].'('.$order['cert_no'].')',
                'goods_name' => $order['goods_title'],
                'setmeal_name' => $order['setmeal_title'],
                'amount' => $order['amount'],
                'setmeal_foregift' => $order['setmeal_foregift'],
                'is_new' => $order['new_grade']<100?'否':'是',
                'meal' => $order['pact_type'],
                'total_rent1' => $order['rent_total'].'元',
                'month_total' => $order['month_total'],
                'first_month_rent'=>$fisrt_month_rent,
                'month_rent' => $month_rent.'元'.'（月租金=(总租金-首付金)/期数）',
                'begin_time' =>  date('Y.m.d',strtotime($order['begin_time'])),
                'end_time'=>date('Y.m.d',strtotime($order['end_time'])),
                'lease_term' =>  date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time'])),
                'setmeal_price' => $order['setmeal_price']>0?$order['setmeal_price']:0,
                'user_name1' => $order['cert_name'],
                'user_mobile1' => $order['user_mobile'],
                'user_address1' => $order['address'],
                'email'=>$order['user_email'],
                'first_name' => $shop_user['mechanism'],
                'cash_pledge'=>$cash_pledge,//押金
                'cash_pledge_period'=>$cash_pledge_period,//押金的第几期
                'cash_pledge_deduction'=>$cash_pledge_deduction,//抵充的第几期
            )
        );

        $order_arr['simpleFormFields']=array_merge($order_arr['simpleFormFields'],$repayList);


        $orderLease = OrderLease::getPayTime($order);
        foreach ($orderLease as $k=>$v){
            $order_arr['simpleFormFields']['pay_time'.$v['which_period']] = date('Y年m月d日',$v['begin_time']);
            $order_arr['simpleFormFields']['month_rent'.$v['which_period']] = $v['rent'].'元';
        }
        if(count($orderLease) < 12){
            $lastNum = count($orderLease)+1;
            for($i=$lastNum;$i<=12;$i++){
                $order_arr['simpleFormFields']['pay_time'.$i] = '---';
                $order_arr['simpleFormFields']['month_rent'.$i] = '---';
            }
        }


        $fileId = self::createByTemplate($order_arr);
        if(!empty($shop_user['esign_shop_id'])){
            self::SetSignAuth($shop_user['esign_shop_id']);//设置静默签署
            self::SetSignAuth(config('esignDlz.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'商户签署账号不存在'];
        }
        //发起签署
        $arr = array(
            'docs' => array(
                0 => array(
                    'fileId' => $fileId,
                    'fileName' => '都来租租赁合同.pdf'
                )
            ),
            'flowInfo' => array(
                'autoArchive' => true,
                'autoInitiate' => true,
                'businessScene' => '租赁合同',
                'flowConfigInfo' => array(
                    'redirectUrl' => 'wechat://back',
                    'noticeDeveloperUrl' => config('alipay.callbackDomain').CommonService::NOTICE_SUPPLIER_URL_CONTRACT,
                    'willTypes'=>['FACE_WE_CHAT_FACE']
                ),
                'initiatorAccountId' => config('esignDlz.ACCOUNT'),
                'initiatorAuthorizedAccountId' => config('esignDlz.ACCOUNT')
            ),
            'signers' => array(
                //企业自动签署
//                0=>array(
//                    'platformSign' => false,
//                    'signerAccount' => array(
//                        'authorizedAccountId' => $shop_user['esign_shop_id'],
//                    ),
//                    'signfields' => array(
//                        0=>array(
//                            'autoExecute' => true,
//                            'actorIndentityType' => 2,
//                            'fileId' => $fileId,
//                            'sealType' => 2,
//                            'sealId' => $shop_user['esign_seal_id'],
//                            'posBean' => array(
//                                'posPage' => 16,
//                                'posX' => 190,
//                                'posY' => 679
//                            )
//                        )
//                    )
//                ),
                //个人手动签署
                0=>array(
                    'signerAccount' => array(
                        'signerAccountId' => $esign_user_id,
                    ),
                    'signfields' => array(
                        0=> array(
                            'autoExecute' => false,
                            'fileId' => $fileId,
                            'sealType' => 1,
                            'handDrawnWay'=>1,
                            'posBean' => array(
                                'posPage' => 17,
                                'posX' => 412,
                                'posY' => 216
                            )
                        )
                    )
                ),
                //平台自动签署
                1=>array(
                    'platformSign' => false,
                    'signerAccount' => array(
                        'authorizedAccountId' => config('esignDlz.ACCOUNT'),
                    ),
                    'signfields' => array(
                        0=>array(
                            'autoExecute' => true,
                            'actorIndentityType' => 2,
                            'fileId' => $fileId,
                            'sealType' => 2,
                            'sealId' => config('esignDlz.SEALID'),
                            'posBean' => array(
                                'posPage' => 17,
                                'posX' => 145,
                                'posY' => 99
                            )
                        )
                    )
                ),
                2=>array(
                    'signerAccount' => array(
                        'signerAccountId' => $esign_user_id,
                    ),
                    'signfields' => array(
                        0=> array(
                            'autoExecute' => false,
                            'fileId' => $fileId,
                            'sealType' => 1,
                            'handDrawnWay'=>1,
                            'posBean' => array(
                                'posPage' => 21,
                                'posX' => 420,
                                'posY' => 414
                            )
                        )
                    )
                ),
            ),
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.createFlowOneStep'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('一步发起签署-三方合同',$data,$return_content);
        return $result;
    }



    // 1 创建企业法人账号
    public static function applyByFile(){
        $arr = array(
            'docs'=>['68c7dcdc0a9e409fa5836b74436d34d4','cad04c2525864e358b2fc2fb17b1974e'],
            'applyConfig'=>[
            "reportTemplate"=>"15",
            "signProductType"=> "1",
            "realNameType"=> "1",
            "willingnessType"=>"1"
         ]
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esignDlz.addPersonAccountID'),$data,config('esignDlz.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('申请e签宝验签报告',$data,$return_content);
        if(isset($result['data']) && !empty($result['data']['accountId'])){
            return $result['data']['accountId'];
        }
    }

    /**
     * qn-个人信信息报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createQnRiskUserAuth($order){
        $simpleFormFields=array(
            "name" => $order['cert_name'], //姓名
            "year" => date("Y"),
            "month" => date("m"),
            "day" => date("d")
        );
        fopen('/www/wwwroot/api.doulaizuji.com/public/pdf/'.$order['trade_no'].'qnyp.pdf', 'w');
        $data = [
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/api.doulaizuji.com/public/个人信息授权书qnyp.pdf',
                    'dstPdfFile'=>'/www/wwwroot/api.doulaizuji.com/public/pdf/'.$order['trade_no'].'qnyp.pdf',
                ],
                'txtFields'=>$simpleFormFields
            ])
        ];
        $return_content = self::doMultipart(config('esignDlz.API_HOST_V3').'/timevale/doc/createFileFromTemplate',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //个人
        $flowId=AuthenticLog::where('order_id',$order['id'])->orderbY('id','desc')->where('status',1)->value('certify_id');
        $data = [
            'personSignParam'=>json_encode([
                'accountId'=>$order['esign_user_id'],
                'sealData'=>$order['esign_seal_id'],
                'willingnessId'=>$flowId,
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/api.doulaizuji.com/public/pdf/'.$order['trade_no'].'qnyp.pdf',
                    'dstPdfFile'=>'/www/wwwroot/api.doulaizuji.com/public/pdf/'.$order['trade_no'].'qnyp.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 2,
                        'posX' => 470,
                        'posY' => 145
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esignDlz.API_HOST_V3').'/timevale/user/sign/personSign',$data);

        self::addLog('一步发起签署-个人信息报告qn授权书',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }

        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'message'=>'合同生成成功','data'=>$result];



    }

}
